﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using T.ServiceComponent.Error;
using T.ServiceComponent.Kernel.Service;
using  T.ServiceFramework.ServiceGateway.Client;
using  T.ServiceFramework.ServiceGateway.SPI;
using ConfigManager = T.ServiceComponent.Config.Client.ConfigManager;

namespace T.FAS.Runtime.Base.Entity
{
    public class FASResultResponseExtension : IResponseExtension
    {
        private const string configcenter_DebugModeKey = "TTP.SG.CommonResponseExtension.IsDebugMode";
        public object Error(TException e)
        {
            var message = string.Empty;
            if (e.InnerException != null)
            {
                var innerException = e.InnerException;
                while (innerException.InnerException != null)
                {
                    innerException = innerException.InnerException;
                }

                message = innerException.Message;
            }
            else
            {
                message = e.Message;
            }

            if (GetDebugMode())
            {
                message = GetExceptionStackInfo(message, e);
            }

            var tResponse = new TResponse()
            {
                errcode = e.Code,
                errmsg = message,
                state = "0"
            };

            return tResponse;
        }

        public object Response(object result)
        {
            CustomJson();
            if (result is SGExceptionResult)
            {
                var sgResult = result as SGExceptionResult;

                return new TResponse()
                {
                    errcode = sgResult.ErrorCode,
                    errmsg = sgResult.ErrorMessage
                };
            }

            if (result is TBaseResult)
            {
                return ConvertToTResponse(result as TBaseResult);
            }

            var tResponse = new TResponse()
            {
                data = result,
                state = "1"
            };

            return tResponse;
        }

        private TResponse ConvertToTResponse(TBaseResult baseResult)
        {
            var response = new TResponse()
            {
                state = baseResult.ResultState ? "1" : "0",
                errcode = baseResult.ErrorCode,
                errmsg = baseResult.ErrorMessage,
                data = baseResult.ReturnValue
            };

            return response;
        }

        private string GetExceptionStackInfo(string message, Exception ex)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(message);
            sb.AppendLine("Exception Stack:");
            sb.AppendLine(ex.StackTrace);
            var inner = ex.InnerException;
            while (inner != null)
            {
                sb.AppendLine("InnerException Message:" + inner.Message);
                sb.AppendLine("InnerException Stack:" + inner.StackTrace);
                inner = inner.InnerException;
            }
            return sb.ToString();
        }

        /// <summary>
        /// 从配置中心读取是否启用调试模式
        /// </summary>
        /// <returns></returns>
        private bool GetDebugMode()
        {
            bool isDebugMode = false;
            try
            {
                var isDebugModeStr = ConfigManager.GetConfigValue(configcenter_DebugModeKey, true);

                if (!string.IsNullOrWhiteSpace(isDebugModeStr) && (isDebugModeStr.ToLower() == "1" || isDebugModeStr.ToLower() == "true"))
                {
                    isDebugMode = true;
                }
            }
            catch
            {
            }

            return isDebugMode;
        }
        private void CustomJson()
        {
            JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() =>
            {
                JsonSerializerSettings setting = new JsonSerializerSettings();
                //日期类型默认格式化处理  
                setting.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
                setting.DateFormatString = "yyyy-MM-dd HH:mm:ss.fff";
                return setting;
            });
        }

    }
}
